﻿using AutoMapper;
using CoreProject.DTO;
using CoreProject.IService;
using CoreProject.Model;
using Microsoft.AspNetCore.Mvc;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace CoreProject.Api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class MessageController : ControllerBase
    {
        // GET: api/<MessageController>
        private readonly IMessageService _service;
        private readonly IMapper _mapper;

        public MessageController(IMessageService service, IMapper mapper)
        {
            _service = service;
            _mapper = mapper;
        }
        [HttpGet("page")]
        public async Task<ResultPageList<MessageDto>> GetListByPage(int page, int size, string name = "")
        {

            var data = await _service.GetMessageBypage(name, page, size);

            //手动变自动
            var list = _mapper.Map<List<MessageDto>>(data.list);

            ResultPageList<MessageDto> result = new ResultPageList<MessageDto>();
            result.state = 200;
            result.code = "1";
            result.msg = "ok";
            result.page = page;
            result.size = size;
            result.count = data.count;
            result.data = list;
            return result;
        }
        [HttpPost]
        public async Task<ResultHandle> Post([FromBody] MessageDto medto)
        {
            var data = _mapper.Map<Message>(medto);
            data.Time=DateTime.Now;
            var bol = await _service.AddAsync(data);
            ResultHandle result = new ResultHandle();
            result.state = 200;
            result.code = bol ? "1" : "-1";
            result.msg = bol ? "添加成功!" : "添加失败!";
            return result;

        }

        [HttpDelete]
        public async Task<ResultHandle> Delete(int id)
        {
            Message menu = new Message();
            menu.Id = id;
            var bol = await _service.DeleteAsync(menu);
            ResultHandle result = new ResultHandle();
            result.state = 200;
            result.code = bol ? "1" : "-1";
            result.msg = bol ? "删除成功!" : "删除失败!";
            return result;
        }

    }
}
